package InterviewTest.q1711_findClosest;

import java.util.ArrayList;
import java.util.List;

public class Solution_1 {
    /*
    遍历一次words 将所有word1 和 2 对应的索引位置记录到链表中
    然后使用两个指针遍历链表 并且不断更新两个单词之间的最小距离 （遇到1可以直接返回）
     */
    public int findClosest(String[] words, String word1, String word2) {
        List<Integer> word1Index = new ArrayList<>();
        List<Integer> word2Index = new ArrayList<>();

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) word1Index.add(i);
            if (words[i].equals(word2)) word2Index.add(i);
        }

        int p1 = 0, p2 = 0, distance = Integer.MAX_VALUE;
        while (p1 < word1Index.size() && p2 < word2Index.size()) {
            distance = Math.min(distance, Math.abs(word1Index.get(p1) - word2Index.get(p2)));
            if (distance == 1) return 1;
            if (word1Index.get(p1) < word2Index.get(p2)) {
                p1++;
            }else {
                p2++;
            }
        }

        return distance;
    }
}
